package org.practice.dao;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.practice.model.Product;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository(value="productDao")
public class ProductDaoImpl extends HibernateTemplate implements ProductDao {
	private static Logger logger = Logger.getLogger(ProductDaoImpl.class);
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory=sessionFactory;
	}
	public Product findProductById(final Integer id){
		return (Product)this.execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {//session是个代理
				Query query=session.createQuery("select new Product(p.id, p.name, p.fixedPrice, p.dangPrice) from Product p where p.id=?");
				query.setInteger(0, id);
				List<Product> list = query.list();
				if (list.size() > 0) {
					return list.get(0);
				}
				return null;
			}
		});
	}

}
